"use strict";
import axios from 'axios';
import { Message } from 'element-ui';
import router from '@/router.js';
let pathRewrite = '/api';
export default {
  formatterUrl(data) {
    return pathRewrite + data.url + (sessionStorage.getItem("tokenId") ? `?tokenId=${sessionStorage.getItem("tokenId")}` : '')
  },
  service(data, type) {
    let headers = {};
    /**headers */
    switch (type) {
      case 'upload':
        headers = {
          'deviceCode': 'A95ZEF1-47B5-AC90BF3'
        }
        break;
      default:
      headers = {
        'X-Requested-With': 'XMLHttpRequest'
      }
      break;
    }
    const service = axios.create({
      timeout: 30000,
      headers
    });
    /*
     *增加请求拦截器
     */
    service.interceptors.request.use((config) => {
      //预处理请求的信息
      if (config.method === 'post') {
        config.headers.post['Content-Type'] = 'application/x-www-form-urlencoded';
      }
      if (process.env.NODE_ENV === 'development') {
        config.url = type && type !== 'upload' ? (`/${type}` + config.url) : (pathRewrite + config.url);
      }
      config.url = config.url + (sessionStorage.getItem("tokenId") ? `?tokenId=${sessionStorage.getItem("tokenId")}` : '');

      return config
    }, (error) => {
      //预处理请求有异常error时抛出错误
      return Promise.reject(error)
    });
    /*
     *增加响应拦截器
     */
    service.interceptors.response.use((response) => {
      if (response.status === 200) {
        switch (response.data.statusCode){
          case '200':
           return response.data;
          case "401":
            router.replace({
              path: '/login',
              query: {
                redirect: encodeURIComponent(router.history.current.fullPath)
              }
            })
            break;
          default:
          Message.error(response.data.desc);
          return Promise.reject(response.data);
        }
      } else {
        return Promise.reject(response.status)
      }
    }, error => {
      if (error.response) {
        switch (error.response.status) {
          case 401:
            router.replace({
              path: '/login',
              query: {
                redirect: encodeURIComponent(router.history.current.fullPath)
              }
            })
            break;
          case 504:
          case 500:
          case 404:
            Message.error('接口出错');
            break;
          default:
            Message.error('加载失败！ 请重新加载...');
            break;
        }
      }
      return Promise.reject(error)
    })
    return service(data);
  }
}

